<?php
/**
 *  阿里云SMS
 * Class AliSms
 * @package app\lib\sms
 */
declare (strict_types = 1);

namespace app\lib\sms;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use think\facade\Log;

class AliSms implements SmsInterface {

    /**
     * 发送短信验证码
     * @param string $tel
     * @param int $code
     * @param array $options
     * @return bool
     * @throws ClientException
     */
    public static function sendCode(string $tel, int $code) : bool {
        if (empty($tel) || empty($code)) {
            return false;
        }

        AlibabaCloud::accessKeyClient(config("aliyun.accessKeyId"), config("aliyun.accessSecret"))
            ->regionId(config("aliyun.regionId"))
            ->asDefaultClient();

        try {
            $options = config("aliyun.options");
            $options["query"]["PhoneNumbers"] = $tel;
            $options["query"]["TemplateParam"] = json_encode(["code" => $code]);
            $result = AlibabaCloud::rpc()
                ->product(config("aliyun.product"))
                // ->scheme('https') // https | http
                ->version(config("aliyun.version"))
                ->action(config("aliyun.action"))
                ->method(config("aliyun.method"))
                ->host(config("aliyun.host"))
                ->options($options)
                ->request();
            $result = $result->toArray();
            log::info("aliyun sms send code result from $tel:" . json_encode($result));
        } catch (ClientException $e) {
            Log::error("aliyun sms send code error from $tel:". $e->getMessage());
            return false;
        } catch (ServerException $e) {
            Log::error("aliyun sms send code error from $tel:" . $e->getMessage());
            return false;
        }

        if (isset($result["Code"]) && $result["Code"] != "OK") {
            return false;
        }

        return true;
    }
}